package com.hl.mystudy.widget;

import static com.hl.mystudy.widget.MusicWidgetProvider.ACTION_FAVORITE;
import static com.hl.mystudy.widget.MusicWidgetProvider.ACTION_LIST;
import static com.hl.mystudy.widget.MusicWidgetProvider.ACTION_NEXT;
import static com.hl.mystudy.widget.MusicWidgetProvider.ACTION_PLAY_PAUSE;
import static com.hl.mystudy.widget.MusicWidgetProvider.ACTION_PRE;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import androidx.media3.common.MediaItem;
import androidx.media3.exoplayer.ExoPlayer;

import com.hl.mystudy.bean.SongInfo;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @author hyhdez
 * @description : 音乐播放器widget的服务
 * @date 2024/1/15 22:15
 */
public class MusicWidgetService extends Service {
    private static final String TAG = MusicWidgetService.class.getSimpleName();
    private Context mContext;
    private final ArrayList<SongInfo> mSongInfoList = new ArrayList<>(16);

    private final int PLAY_STATE_STOP = 0;
    private final int PLAY_STATE_PLAY = 1;
    private final int PLAY_STATE_PAUSE = 2;
    private int playStatus = PLAY_STATE_STOP;
    private int songSum;
    private int index;
    private ExoPlayer mediaPlayer;

    public MusicWidgetService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        if (!TextUtils.isEmpty(action)) {
            switch (action) {
                case ACTION_PRE:
                    pre();
                    break;
                case ACTION_PLAY_PAUSE:
                    playPause();
                    break;
                case ACTION_NEXT:
                    next();
                    break;
                case ACTION_LIST:
                    list();
                    break;
                case ACTION_FAVORITE:
                    favorite();
                    break;
                default:
                    break;
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void favorite() {

    }

    private void list() {
        mSongInfoList.clear();
        Cursor cursor = null;
        try {
            ContentResolver contentResolver = mContext.getContentResolver();
            Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//            Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
            cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor == null) {
                Log.e(TAG, "MusicWidgetService.list cursor == null");
            } else if (!cursor.moveToFirst()) {
                Log.e(TAG, "MusicWidgetService.list 没有音频文件");
            } else {
                int data = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
                int displayName = cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
                do {
                    String musicName = cursor.getString(displayName);
                    String path = cursor.getString(data);
                    if (path.endsWith("mp3")) {
                        SongInfo songInfo = new SongInfo();
                        songInfo.setTitle(musicName);
                        songInfo.setData(path);
                        mSongInfoList.add(songInfo);
                    }
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
                Log.e(TAG, "MusicWidgetService.list mSongInfoList = " + mSongInfoList.toString());
            }
        }
        for (SongInfo songInfo : mSongInfoList) {
            Log.e(TAG, "MusicWidgetService.list :" + songInfo.getData());
        }
    }

    private void next() {
        mediaPlayer.seekToNextMediaItem();
    }

    private void playPause() {
        if (playStatus == PLAY_STATE_STOP) {
            if (mSongInfoList.isEmpty()) {
                list();
            }
            if (mSongInfoList.isEmpty()) {
                Log.e(TAG, "MusicWidgetService.playPause 没有歌曲");
                return;
            }
            index = 0;
            songSum = mSongInfoList.size();
            doPlay(mSongInfoList, index);
            playStatus = PLAY_STATE_PLAY;
        } else if (playStatus == PLAY_STATE_PLAY) {
            doPause();
            playStatus = PLAY_STATE_PAUSE;
        } else if (playStatus == PLAY_STATE_PAUSE) {
            doResume();
            playStatus = PLAY_STATE_PLAY;
        } else {
            Log.e(TAG, "MusicWidgetService.playPause 状态错误");
        }

    }

    private void doResume() {
        mediaPlayer.setPlayWhenReady(true);
    }

    private void doPause() {
        mediaPlayer.setPlayWhenReady(false);
    }

    private void doPlay(ArrayList<SongInfo> mSongInfoList, int index) {
        Log.e(TAG, "MusicWidgetService.doPlay Enter");
        // 设置音频源，这里使用本地音频文件
        String path = mSongInfoList.get(index).getData();
        Log.e(TAG, "MusicWidgetService.doPlay 开始播放" + path);
        // 创建ExoPlayer实例
        mediaPlayer = new ExoPlayer.Builder(mContext).build();
        // 设置媒体源（本地或网络上的MP3文件）
//        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(path));
//        mediaPlayer.setMediaItem(mediaItem);

//        播放列表
        ArrayList<MediaItem> mediaItems = new ArrayList<>(16);
        for (SongInfo songInfo : mSongInfoList) {
            path = songInfo.getData();
            MediaItem mediaItem = MediaItem.fromUri(Uri.parse(path));
            mediaItems.add(mediaItem);
        }
        mediaPlayer.setMediaItems(mediaItems);

        // 准备播放器
        mediaPlayer.prepare();
        // 开始播放
        mediaPlayer.play();
    }

    private void pre() {
        mediaPlayer.seekToPreviousMediaItem();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            // 停止播放，释放资源
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}